﻿using In66.Net.Elasticsearch;
using In66.Net.Share.Controller;
using Nest;
using System.ComponentModel.DataAnnotations;
using Test.Api.Models.Elasticsearch;

namespace Test.Api.Controllers.V1
{
    /// <summary>
    /// Elasticsearch控制器
    /// </summary>
    [ApiVersion("1.0")]
    [AllowAnonymous]
    [Route("test/[controller]/[action]")]
    public class ElasticsearchController : BaseController
    {
        private readonly IElasticsearchRepository<VisitLog> _visitLogRepository;
        private readonly IElasticsearchRepository<EsTest> _esTestRepository;
        public ElasticsearchController(
            IElasticsearchRepository<VisitLog> visitLogRepository, IElasticsearchRepository<EsTest> esTestRepository)
        {
            _visitLogRepository = visitLogRepository;
            _esTestRepository = esTestRepository;
        }

        [HttpGet]
        [ProducesResponseType(StatusCodes.Status404NotFound)]
        [ProducesResponseType(StatusCodes.Status200OK, Type = typeof(PagedResult<EsTest>))]
        public async Task<IActionResult> SearchPageAsync([FromQuery] EsTestSearch input)
        {
            var mustBuilder=new ElasticsearchBuilder<EsTest>()
                            .Match(!string.IsNullOrWhiteSpace(input.Name), input => input.Name, input.Name)
                            .GreaterThan(input.Age > 0, input => input.Age, input.Age)
                            .Build();

            var shoudBuilder = new ElasticsearchBuilder<EsTest>().Build();

            var mustNotBuilder = new ElasticsearchBuilder<EsTest>().Build();

            Func<QueryContainerDescriptor<EsTest>, QueryContainer> query =q =>q.Bool(a => a.Must(mustBuilder));

            var result = await _esTestRepository.SearchPageAsync(input.PageIndex, input.PageSize, query, sd => sd.Descending(p=>p.CreatedAt));

            return Ok(result);
        }
        
        [HttpPost]
        public async Task<IActionResult> InsertAsync([FromBody] EsTest esTest)
        {
            await _esTestRepository.InsertAsync(esTest);

            return Ok("新增成功");
        }
        [HttpDelete]
        public async Task<IActionResult> DeleteAsync([Required] string id)
        {
            await _esTestRepository.DeleteAsync(id);

            return Ok("删除成功");
        }
        [HttpPut]
        public async Task<IActionResult> UpdateAsync([FromBody] EsTest esTest)
        {
            await _esTestRepository.UpdateAsync(esTest);

            return Ok("修改成功");
        }
    }
}
